package com.example.filesystem.controller;

import com.example.filesystem.dto.FileInfoDTO;
import com.example.filesystem.model.FileInfo;
import com.example.filesystem.service.FileService;
import com.example.filesystem.util.RFC3986;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.List;


@RestController
@RequestMapping("/filetrans/files")
public class FileController {

    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @GetMapping
    public ResponseEntity<List<FileInfoDTO>> listFiles() {
        List<FileInfoDTO> files = fileService.listFilesWithCategory();
        return ResponseEntity.ok(files);
    }

    @GetMapping("/download/{prepareId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable Long prepareId) throws MalformedURLException {
        FileInfo fileInfo = fileService.getPrepare(prepareId);

        if (fileInfo != null) {
            Path filePath = fileService.getFilePath(fileInfo.getFilePath());
            Resource resource = new UrlResource(filePath.toUri());
            // 标准化文件名处理，使用RFC3986编码（兼容所有浏览器）
            String encodedFilename = RFC3986.encode(fileInfo.getFilename()).replace("+", "%20");

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFilename + "\"")
                    .body(resource);
        } else {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"empty\"")
                    .body(new ByteArrayResource(new byte[1]));
        }
    }

    @GetMapping("/prepare/{fileId}")
    public ResponseEntity<Long> prepare(@PathVariable Long fileId) {
        Long prepareId = fileService.prepare(fileId);
        return ResponseEntity.ok(prepareId);
    }

    @DeleteMapping("/{fileId}")
    public ResponseEntity<Void> deleteFile(@PathVariable Long fileId) throws IOException {
        boolean deleteFile = fileService.deleteFile(fileId);
        if (deleteFile) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.status(500).build();
    }

    // 初始化分片上传
    @PostMapping("/upload/init")
    public ResponseEntity<?> initUpload(@RequestParam String fileName,
                                        @RequestParam Long fileSize,
                                        @RequestParam Long lastModified,
                                        @RequestParam Integer chunkSize,
                                        @RequestParam(required = false) Long categoryId) {
        String uploadId = fileService.initUpload(fileName, fileSize, lastModified, chunkSize, categoryId);
        return ResponseEntity.ok().body(uploadId);
    }

    // 上传分片
    @PostMapping("/upload/chunk")
    public ResponseEntity<?> uploadChunk(@RequestParam String uploadId,
                                         @RequestParam Integer chunkNumber,
                                         @RequestParam String hash,
                                         @RequestParam MultipartFile chunk) {
        fileService.uploadChunk(uploadId, hash, chunkNumber, chunk);
        return ResponseEntity.ok().build();
    }

    // 检查分片
    @PostMapping("/check/chunk")
    public ResponseEntity<?> checkChunk(@RequestParam String uploadId,
                                        @RequestParam Integer chunkNumber,
                                        @RequestParam String hash) {
        Integer i = fileService.checkChunk(uploadId, hash, chunkNumber);
        return ResponseEntity.ok().body(i);
    }

    // 完成上传
    @PostMapping("/upload/complete")
    public ResponseEntity<?> completeUpload(@RequestParam String uploadId) {
        String fileId = fileService.completeUpload(uploadId);
        return ResponseEntity.ok().body(fileId);
    }

    // 获取上传进度
    @GetMapping("/upload/progress/{uploadId}")
    public ResponseEntity<?> getUploadProgress(@PathVariable String uploadId) {
        int progress = fileService.getUploadProgress(uploadId);
        return ResponseEntity.ok().body(progress);
    }
}